package com.atguigu.boot04.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author:朱思博
 * @date:2021/5/8-{13:01} 登录拦截器
 *
 * 1.编写一个拦截器实现HandlerInterceptor接口，或继承类
 * 2.把这些配置放在IOC容器中，实现WebMvcConfigurer接口的addInterceptors()方法
 * 3.指定拦截规则
 */
public class LoginInterceptor implements org.springframework.web.servlet.HandlerInterceptor {
    // 目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginUser");

        if (user != null) {
            return true;
        }

        // 拦截住了，代表未登录，自然就应该跳转到登录界面
//        request.setAttribute("msg","被拦截器拦截，请先登录");
//        request.getRequestDispatcher("/").forward(request,response);
        // ${msg}

        session.setAttribute("msg","被拦截器拦截，请先登录");
        response.sendRedirect("/");
        // ${session.msg}
        return false;
    }
}
